#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import sys
import os
from collections import Counter

def analyze_value(value, path="root", max_depth=3, current_depth=0, max_items=5):
    """分析JSON值的结构"""
    if current_depth >= max_depth:
        return f"达到最大深度 {max_depth}"
    
    if isinstance(value, dict):
        if not value:
            return "空对象 {}"
        
        if len(value) > max_items:
            keys = list(value.keys())[:max_items]
            result = f"对象 {{键数量: {len(value)}, 部分键: {keys}...}}"
            
            # 分析一些键的值类型
            for k in keys:
                child_path = f"{path}.{k}"
                child_value = value[k]
                child_type = type(child_value).__name__
                
                if isinstance(child_value, (dict, list)):
                    result += f"\n  - {child_path}: {child_type}"
                    if current_depth + 1 < max_depth:
                        child_result = analyze_value(child_value, child_path, max_depth, current_depth + 1, max_items)
                        result += f" => {child_result}"
                else:
                    sample = str(child_value)
                    if len(sample) > 50:
                        sample = sample[:50] + "..."
                    result += f"\n  - {child_path}: {child_type} = {sample}"
            
            return result
        else:
            result = "对象 {"
            for k, v in value.items():
                child_path = f"{path}.{k}"
                child_result = analyze_value(v, child_path, max_depth, current_depth + 1, max_items)
                result += f"\n  - {k}: {child_result}"
            result += "\n}"
            return result
    
    elif isinstance(value, list):
        if not value:
            return "空数组 []"
        
        # 计算值类型的分布
        type_counter = Counter(type(item).__name__ for item in value)
        type_info = ", ".join(f"{t}={c}" for t, c in type_counter.items())
        
        if len(value) > max_items:
            result = f"数组 [长度: {len(value)}, 类型: {type_info}]"
            
            # 分析一些数组元素
            for i in range(min(max_items, len(value))):
                child_path = f"{path}[{i}]"
                child_result = analyze_value(value[i], child_path, max_depth, current_depth + 1, max_items)
                result += f"\n  - {child_path}: {child_result}"
            
            return result
        else:
            result = f"数组 [长度: {len(value)}, 类型: {type_info}]"
            for i, item in enumerate(value):
                child_path = f"{path}[{i}]"
                child_result = analyze_value(item, child_path, max_depth, current_depth + 1, max_items)
                result += f"\n  - {i}: {child_result}"
            result += "\n]"
            return result
    
    else:
        # 基本类型值
        type_name = type(value).__name__
        value_str = str(value)
        if len(value_str) > 100:
            value_str = value_str[:100] + "..."
        return f"{type_name} = {value_str}"

def analyze_json_file(file_path, max_depth=3, max_items=5):
    """分析JSON文件结构"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        file_size = os.path.getsize(file_path)
        file_size_str = f"{file_size / 1024:.2f} KB" if file_size < 1024 * 1024 else f"{file_size / 1024 / 1024:.2f} MB"
        
        print(f"文件: {file_path}")
        print(f"文件大小: {file_size_str}")
        print(f"根级结构:")
        
        if isinstance(data, dict):
            print(f"顶层是一个对象，包含 {len(data)} 个键:")
            for key in data:
                print(f"  - {key}: {type(data[key]).__name__}")
            
            print("\n详细结构分析:")
            print(analyze_value(data, max_depth=max_depth, max_items=max_items))
            
        elif isinstance(data, list):
            print(f"顶层是一个数组，包含 {len(data)} 个元素")
            
            # 尝试检测是否是试卷或题目数组
            if len(data) > 0:
                first_item = data[0]
                if isinstance(first_item, dict):
                    sample_keys = list(first_item.keys())
                    print(f"  首个元素是对象，包含键: {sample_keys}")
                    
                    # 检测是否为试卷
                    if 'questionIds' in first_item or ('name' in first_item and 'id' in first_item):
                        print("  推测为试卷数组")
                    # 检测是否为题目
                    elif 'title' in first_item or 'detail' in first_item or 'options' in first_item or 'answer' in first_item:
                        print("  推测为题目数组")
            
            print("\n详细结构分析:")
            print(analyze_value(data, max_depth=max_depth, max_items=max_items))
            
        else:
            print(f"顶层是一个基本类型: {type(data).__name__}")
            print(data)
        
    except json.JSONDecodeError as e:
        print(f"JSON解析错误: {e}")
    except Exception as e:
        print(f"分析时出错: {e}")

if __name__ == '__main__':
    if len(sys.argv) > 1:
        file_path = sys.argv[1]
    else:
        file_path = input("请输入JSON文件路径: ")
    
    max_depth = 3
    max_items = 5
    
    if len(sys.argv) > 2:
        try:
            max_depth = int(sys.argv[2])
        except:
            pass
    
    if len(sys.argv) > 3:
        try:
            max_items = int(sys.argv[3])
        except:
            pass
    
    analyze_json_file(file_path, max_depth, max_items)
    
    print("\n使用方法:")
    print("python analyze_json_structure.py 文件路径 [最大深度=3] [最大项目数=5]")
    print("例如: python analyze_json_structure.py indexeddb_export.json 4 10") 